package com.ycs.operationlog.service;

import cn.hutool.core.date.DateUtil;
import com.ycs.operationlog.config.DataSourceConfig;
import com.ycs.operationlog.entity.OperateLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * 异步调用日志服务
 *
 * @author ycs
 */
@Service
public class AsyncLogService {

    @Autowired
    private DataSourceConfig dataSourceConfig;

    /**
     * 保存系统日志记录
     */
    @Async
    public void saveSysLog(OperateLog operateLog) {
        JdbcTemplate jdbcTemplate = dataSourceConfig.getJdbcTemplate();
        String sql = "INSERT INTO `sys_operate_log` (`oper_id`, `title`, `business_type`, `method`, `request_method`, `operator_type`, `oper_name`, `dept_name`, `oper_url`, `oper_ip`, `oper_location`, `oper_param`, `json_result`, `status`, `error_msg`, `oper_time`) VALUES (null , ?, ?, ?, ?, ?, ?, ?,?, ?, ?, ?, ?, ?,? ,?);";
        jdbcTemplate.update(sql, preparedStatement -> {
            preparedStatement.setString(1, operateLog.getTitle());
            preparedStatement.setInt(2, operateLog.getBusinessType());
            preparedStatement.setString(3, operateLog.getMethod());
            preparedStatement.setString(4, operateLog.getRequestMethod());
            preparedStatement.setInt(5, operateLog.getOperatorType());
            preparedStatement.setString(6, operateLog.getOperName());
            preparedStatement.setString(7, operateLog.getDeptName());
            preparedStatement.setString(8, operateLog.getOperUrl());
            preparedStatement.setString(9, operateLog.getOperIp());
            preparedStatement.setString(10, operateLog.getOperLocation());
            preparedStatement.setString(11, operateLog.getOperParam());
            preparedStatement.setString(12, operateLog.getJsonResult());
            preparedStatement.setInt(13, operateLog.getStatus());
            preparedStatement.setString(14, operateLog.getErrorMsg());
            preparedStatement.setString(15, DateUtil.format(operateLog.getOperTime(),"yyyy-MM-dd HH:mm:ss"));
        });

    }
}
